﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Shares/ShareSpace.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="AjaxShowCase_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="cphHead" Runat="Server">

    <style type="text/css">
        .hide
        {
            display:none;	
        }
        .red{background-color:Red;}
        .green{background-color:Green;}
        .correct{background-color:Green;}
        .incorrect{background-color:Red;}
    </style>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphBody" Runat="Server">

    <asp:ScriptManagerProxy ID="smp" runat="server"></asp:ScriptManagerProxy>

    <button type="button"   onclick='submitExam(true);'>ส่งข้อสอบ</button>
    <button type="button"   onclick='showConsole();'>แสดงดีบั๊ก</button>

    <div id='dvConsole'>
        <textarea id='TraceConsole' cols='80' rows='12'></textarea>
    </div>


    <div style='width:300px; float:left;'>
        <div id='q_navigatorLeft'>
            <table>
                <thead>
                    <tr>
                        <td>No.</td>
                        <td>Marked</td>
                        <td>Done</td>
                    </tr>

                </thead>
                <tbody id='tr_nav'>
      <%--              <tr>
                        <td><a href='#'>1</a></td>
                        <td><input num='1' type='checkbox' /></td>
                        <td><input num='2' type='checkbox' /></td>
                    </tr>--%>
                </tbody>
            </table>
        </div>

    </div>
    
    <div style='width:auto; float:left;'>
    
    <div id='dvSubjectTop'>
    
        
        <label>เหลือเวลา</label> : <span id='spCountdown'></span>
    </div>
    
    <div id='dv_exam_container'>
    
        <div id='' class='question_box'>
        
            <div class='question_box_q'>
                <b></b>
            </div>
            
            <div class='question_box_c'>
                <div class=''><input type="radio" /></div>
                <div class=''></div>
            </div>
            
            <div class='question_box_a'>
            
            </div>
        
        </div>
    
    </div>
    
    <br />
    <div id='q_navigator' style='display:none;'>
<%--        <a href='#'>1</a>
        <a id='nav_2' href='#'>2</a>
        <a id='nav_3' href='#'>3</a>--%>
    </div>
    
    </div>



    <script type="text/javascript">

        var Remain = 0;

        function loadExam(testingId) { 

            $.ajax({
                type: "POST",
                url: '/Web/DataServices.asmx/GetExam',
                data: "{'testingId':" + testingId + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    AjaxSucceeded(msg);
                },
                error: AjaxFailed
            });

        }

        function markDone() {
            $.map($('.question_box input[type=radio][num]'), function(n, i) {

                if ($(n).attr('checked')) {
                    $('#cbDone_' + $(n).attr('num')).attr('checked','checked');
                }

            });
        }

        function AjaxSucceeded(result) {
            
            var obj = eval('(' + result.d + ')');
            var TestingId = obj.TestingId;
            var Title = obj.Title;
            var Time = obj.Time;
            var ExamType = obj.ExamType;
            var SubjectName = obj.SubjectName;
            var TestingName =  obj.TestingName;
            var SubjectCategoryName = obj.SubjectCategoryName;
            var Description = obj.Description;
            var Questions = obj.Questions;
            var Total = obj.Total;
            Remain = obj.Time;
    
            var output = '';
            countDown();
            setInterval('countDown();',1000*60);
            
            //Populate questions
            $.map(Questions, function(n, i) {

                var iQuestion = n;
                var iWriter = '';

                var iHTemplate = "<div id='q_{0}' q='{0}' num='{2}' class='question_box {3}'>";
                iHTemplate += "<div class='question_box_q'><div><input num='{2}' id='cbMarkQ_{2}' type='checkbox'  onclick='markChoice(this);' />{2}</div>{1}";
                iHTemplate += "</div>";

                iWriter += String.format(iHTemplate, n.QuestionId, n.Description, i + 1, i != 0 ? 'hide' : '');

                $.map(n.Choices, function(o) {
                    var iChoice = o.Choices;
                    var iBTemplate = "<div class='question_box_c'>";
                    iBTemplate += "<div class=''><input num='{4}' onclick='markDone();' name='{2}' clb='{3}' is_correct='{0}' conflict='false' type=\"radio\" \/></div>";
                    iBTemplate += "<div class=''>{1}</div>";
                    iBTemplate += "</div>";

                    iWriter += String.format(iBTemplate, o.IsCorrect, o.Detail, n.QuestionId, o.Label,i+1);
                });

                var iFTemplate = "<div class='question_box_a'>{0}";
                iFTemplate += "</div>";
                iFTemplate += "</div>";

                iWriter += String.format(iFTemplate, n.Answer);
                output += iWriter;


                //var navF = String.format("<a onclick='showQuetion({0});' href='#'>{0}</a>", i + 1);
                //$('#q_navigator').before(navF);
                

                var iLTemplate = "<tr>";
                iLTemplate += "<td><a href='#' onclick='showQuetion({0}); markChoice(this);'>{0}</a></td>";
                iLTemplate += "<td><input id='cbMarkF_{0}' num='{0}' type='checkbox' /></td>";
                iLTemplate += "<td><input readonly='readonly' id='cbDone_{0}' num='{0}' type='checkbox' /></td>";
                iLTemplate += "</tr>";


                var navL = String.format(iLTemplate, i + 1);
                $('#tr_nav').before(navL);
            });


            $('#dv_exam_container').html(output);
            Sys.Debug.traceDump(output, 'generated data');
            //console.log(output);
        }
        
        function AjaxFailed(result) {
            alert(result.status + ' ' + result.statusText);
        }

        function pageLoad() {
            loadExam(2341);
        }

        function markChoice(obj) {

            var no = $(obj).attr('num');
            var marked = $(obj).attr('checked');
            $(String.format('#cbMarkC_{0},#cbMarkF_{0}', no)).attr('checked',marked);
        
        }

        function submitExam(calculateScore) {

            var pObj = manipulatePostObject(calculateScore);
            
            $.ajax({
                type: "POST",
                url: '/Web/DataServices.asmx/GetExamResult',
                data: "{'examSubmitObject':''}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: showAnswers,
                error: AjaxFailed
            });


            

        }

        function showAnswers(result) {
            var rs = result.d;
            var obj = eval('(' + result.d + ')');

            $.map($('input[num][type=radio]'), function(n) {
                var pDiv = $($(n).parent().get(0));
                $(n).attr('conflict', $(n).attr('is_correct') != $(n).attr('checked'));

                if ($(n).attr('conflict')) {
                    pDiv.addClass('incorrect');
                }



//                if ($(n).attr('is_correct') == $(n).attr('checked')) {
//                    if ($(n).attr('checked')) {
//                        $(n).attr('conflict', false);
//                        pDiv.addClass('correct');
//                    }
//                    else {
//                        $(n).attr('conflict', true);
//                    }
//                }
//                else {
//                    if ($(n).attr('checked')) {
//                        $(n).attr('conflict', true);
//                    }
//                    else {
//                        $(n).attr('conflict', false);
//                    }
//                }

//                if ($(n).attr('conflict')) {
//                    pDiv.addClass('incorrect');
//                }

            });
            
        }

        function manipulatePostObject(calculateScore) {
            var answers = Array();
            var clientObject = { 'TestingId': 0, 'CalculateScore': calculateScore, 'Answers': answers };
            var curDiv = $('#dv_exam_container');
            $.map(curDiv.find('div[id^=q_]'), function(n, i) {

                var iChoices = $(n).find('input[type=radio]');
                for (j = 0; j < iChoices.length; j++) {

                    var jRad = iChoices[j];
                    if ($(jRad).attr('checked')) {
                        answers.push(
                            { 'QuestionId': $(n).attr('q'), 'SelectedChoice': $(jRad).attr('clb') }
                        );
                    }
                }
            });
            return clientObject;
        }




        function countDown() {
            $('#spCountdown').text(Remain--);

            if (Remain < 6) {
                $('#spCountdown').addClass('red');
                $('#spCountdown').removeClass('green');
            }
            else {
                $('#spCountdown').addClass('green');
                $('#spCountdown').removeClass('red');
            }

            if (Remain < 0) {
                alert('เวลาหมดแล้ว ระบบจะทำการส่งคำตอบโดยอัตโนมัต');
                submitExam(true);
            }
        }

        function showQuetion(q) {


            $.map($('div[num]'), function(n, i) {

                if ($(n).attr('num') == q) {
                    $(n).show();
                }
                else {
                    $(n).hide();
                }
            })

        }

        function showConsole() {


            $('#dvConsole').toggle(
                function() { $('#dvConsole').show(); },
                function() { $('#dvConsole').hide(); }
            );
        
        
        }
        
    
    </script>

</asp:Content>

